#include "qgetfile.h"

#include <QMessageBox>
QGetFile::QGetFile(QObject *parent) :
    QObject(parent),
    m_reply(NULL),
    m_timer(new QTimer(this))
{
  connect(m_timer,SIGNAL(timeout()),this,SLOT(timer()));
}

QGetFile::~QGetFile()
{
    stop();
}

void QGetFile::start(const QUrl &url)
{
    if(m_reply!=NULL)
    {
        return;
    }
    QNetworkRequest re(url);
    //re.setAttribute(QNetworkRequest::CacheLoadControl,QNetworkRequest::AlwaysNetwork);
    re.setAttribute(QNetworkRequest::HttpPipeliningAllowedAttribute,true);
    m_reply = m_manager.get(re);

    connect(m_reply, SIGNAL(finished()),
            this, SLOT(finished()));
    connect(m_reply, SIGNAL(readyRead()),
            this, SLOT(readyRead()));
    connect(m_reply,SIGNAL(downloadProgress(qint64,qint64)),
            this,SIGNAL(progress(qint64,qint64)));

    m_last_time=QDateTime::currentDateTime();
    m_timer->start(100);

    m_file.setFileName("./temp/new_version.exe");
    m_file.open(QFile::ReadWrite);
    m_file.resize(0);
}

void QGetFile::stop()
{
    m_file.close();
    if(m_reply!=NULL)
    {
        m_reply->abort();
        m_reply=NULL;
    }
    m_timer->stop();
}


void QGetFile::finished()
{
    if(m_file.isOpen())
    {
        stop();
        emit finish();
    }
}

void QGetFile::readyRead()
{
    m_file.write(m_reply->readAll());
    m_last_time=QDateTime::currentDateTime();
}

void QGetFile::timer()
{
    if(m_last_time.msecsTo(QDateTime::currentDateTime())>5000)
    {
        m_file.close();
        emit offline();
        m_file.remove();
        stop();
    }
}
